package cn.itsource.pethome.service.impl;

import cn.itsource.pethome.domain.Department;
import cn.itsource.pethome.domain.DepartmentDTO;
import cn.itsource.pethome.mapper.DepartmentMapper;
import cn.itsource.pethome.service.DepartmentService;
import cn.itsource.pethome.util.TreeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    DepartmentMapper departmentMapper;



    @Override
    public List<Department> findAll() {
        return departmentMapper.loadAll();
    }

    public List<Department> getDeptTree() {
        // 1. 一次性查询出所有数据，放到内存中，可以使用map  -  做缓存用
        // 2. 从所有数据中找出第一层级/顶级部门：这就是我们需要返回的数据
        // 3. 遍历所有部门只要不是第一层级的，找自己的上级，并将自己放入上级的children中
        //将所有的部门撞到map中  - 每次获取父部门都从这里获取
        List<Department> all = departmentMapper.loadAll();
        Map<Long, Department> map = new HashMap<>();
        for (Department department : all) {
            map.put(department.getId(), department);
        }

        //前端需要得到的集合数据 - 部门树
        List<Department> deptTree = new ArrayList<>();
        for (Department department : all) { //循环置值
            if (department.getParentId() == null ||department.getParentId() == 0 ) {//顶级部门的情况
                deptTree.add(department);
            } else {//不是顶级部门的情况
                //1.想办法找到当前部门的 父部门
                Long parent_id = department.getParentId();

                //从上面的Map中去获取的 - 以前装进去的对象还是会存在
                Department parentDepartment = map.get(parent_id);
                if (parentDepartment != null) {  //防止空指针，过滤出错数据
                    //2.将自己装到  父部门 的children中
                    parentDepartment.getChildren().add(department);
                }
            }
        }
        return deptTree;
    }

    @Override
    public List<Department> getTree() {
        return  TreeUtil.getTree(departmentMapper.loadAll());
    }

    @Override
    public PageInfo<Department> findPage(DepartmentDTO dto) {
        //1.创建分页条件
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        //2.通过条件进行数据查询
        List<Department> departments=departmentMapper.findPage(dto);
        //3.交给pageInfo
        PageInfo<Department> departmentPageInfo = new PageInfo<>(departments);

        return departmentPageInfo;
    }

    @Override
    public void insert(Department department) {
        departmentMapper.insert(department);
    }


}
